var app = new Vue({
    el: '#search',
    data () {
        return {
            sortTab: [ // 排序显示
                {
                    title: '综合'
                },
                {
                    title: '价格'
                },
                {
                    title: '价差率'
                }
            ],
            tabIndex: 0, // 当前排序tab下标
            key: '', // 搜索关键字
            searchKey: '', // 分类跳转进来地址栏参数分类名
            categoryId: null, // 分类跳转进来地址栏参数分类Id
            barcode: '', // 首页扫码跳转进来地址栏参数条码
            position: 'bottom', // 加入购物车弹窗位置
            num: 1, // 加入购物车商品数量
            showPopup: false, // 更多超市价格弹窗是否展示
            popupTop: '', // 更多超市价格弹窗位置
            addCartIndex: 0, // 加入购物车弹窗当前商品下标
            popupIndex: 0, // 更多超市价格弹窗当前商品下标
            popupTriangle: '', // 更多超市价格弹窗三角位置
            triangleStyle: '', // 更多超市价格弹窗样式
            scrollTop: 0, // 页面当前偏移量
            searchData: null, // 搜索结果数据
            orderType: 'NORMAL', // 排序 NORMAL 综合，PRICE_UP 价格升序，PRICE_DOWN 价格降序，SPREAD_DOWN 价差降序
            scrollOptions: {
                pullUpLoad: {
                    threshold: 0,
                    txt: {
                        noMore: '没有更多了！'
                    }
                }
            },
            loading: true, // true 关闭无限加载，false 打开无限加载
            currentPage: 1,
            pageSize: 20,
            totalPage: 2,
            marketData: null, // 更多超市价格弹窗数据
            showSearchHistory: true, // 是否显示搜索历史记录
            searchHistory: null, // 搜索历史记录
            scrollY: 0, // 商品列表滑动的Y坐标
            scrollUp: true, // true 商品列表为上滑，false 下滑
            isSearch: true, // true 顶部显示搜索按钮，false 顶部显示功能直达省略号按钮
            isFunction: false, // true 展开功能直达，false 收回功能直达
            isFunctionMask: false, // true 展开功能直达遮罩层，false 收回功能直达遮罩层
            cartBadge: null,
            sendFriends: '',
            sendCircle: '',
            isAndroid: true
        }
    },
    created () {
        this.getSearchData()
        this.WeChatInit()
        this.WeChatShare()
        this.isSystem()
    },
    watch: {
        scrollY (newVal, oldVal) {
            if (newVal < 0) {
                if (newVal > oldVal) {
                    this.scrollUp = true
                } else {
                    this.scrollUp = false
                }
            } else {
                this.scrollUp = true
            }
        }
    },
    methods: {
        // 返回
        goback () {            
            let url = document.referrer
            if (url.indexOf('search') === -1) {
                window.location.href = '../'
            } else {
                window.location.href = 'searchCategory.html'
            }            
        },
        // 顶部搜索框获取焦点
        focusSearch () {
            this.isSearch = true
        },
        // 顶部搜索框失去焦点
        blurSearch () {
            this.isSearch = false
        },
        // 清除地址栏barcode和searchKey参数
        changeUrl () {
            let barcode = getUrlParams().barcode
            let searchKey = getUrlParams().searchKey
            if (barcode) {
                let state = {title:'',url:window.location.href}
                history.pushState(state, '' ,'/search/searchList.html')
            }
            if (searchKey) {
                let url = this.funcUrlDel('searchKey')
                let state = {title:'',url:window.location.href}
                history.pushState(state, '' ,url)
            }
        },
        // 删除url中指定参数
        funcUrlDel(name){
            let loca = window.location
            let baseUrl = loca.origin + loca.pathname + "?"
            let query = loca.search.substr(1)
            if (query.indexOf(name)>-1) {
                let obj = {}
                let arr = query.split("&")
                for (let i = 0; i < arr.length; i++) {
                    arr[i] = arr[i].split("=")
                    obj[arr[i][0]] = arr[i][1]
                }
                delete obj[name]
                let url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&")
                return url
            }
        },
        // 获取商品列表滚动当前Y坐标
        onScrollHandle (e) {
            this.scrollY = e.y
        },
        // 搜索按钮
        search (e) {
            if (e.keyCode === 13) {
                this.currentPage = 1
                this.searchData = null
                this.orderType = 'NORMAL'
                this.tabIndex = 0
                if (this.key) {
                    this.showSearchHistory = false
                    this.getSearchData()
                } else {
                    this.getSearchHistory()
                    this.showSearchHistory = true
                }
            }
        },
        clickSearch () {
            this.currentPage = 1
            this.searchData = null
            this.orderType = 'NORMAL'
            this.tabIndex = 0
            if (this.key) {
                this.showSearchHistory = false
                this.getSearchData()
            } else {
                this.getSearchHistory()
                this.showSearchHistory = true
            }
        },
        // 点击搜索历史搜索
        searchType (item) {
            let searchType = item.searchType
            if (searchType === 'barcode') {
                this.barcode = item.key
                this.key = item.key
            } else if (searchType === 'category') {
                let key = item.key.split('/')
                this.searchKey = key[0]
                this.key = key[1]
                this.categoryId = item.categoryId
            } else if (searchType === 'searchKey') {
                this.searchKey = item.key
                this.key = item.key
                this.categoryId = item.categoryId
            } else {
                this.key = item.key
            }
            this.changeUrl()
            this.currentPage = 1
            this.searchData = null
            this.orderType = 'NORMAL'
            this.tabIndex = 0
            this.isSearch = false
            this.getSearchData()
        },
        // 更改排序
        changeTab (index) {
            this.tabIndex = index
            this.currentPage = 1
            this.searchData = null
            if (index === 0) {
                this.orderType = 'NORMAL'
                this.getSearchData()
            } else if (index === 1) {
                if (this.orderType === 'NORMAL' || this.orderType === 'PRICE_DOWN' || this.orderType === 'SPREAD_DOWN') {
                    this.orderType = 'PRICE_UP'
                    this.getSearchData()
                } else if (this.orderType === 'PRICE_UP') {
                    this.orderType = 'PRICE_DOWN'
                    this.getSearchData()
                }
            } else if (index === 2) {
                this.orderType = 'SPREAD_DOWN'
                this.getSearchData()
            }
        },
        // 搜索无限加载
        searchMore() {
            this.currentPage ++
            if(this.currentPage > this.totalPage){
                this.loading = true
                this.$refs.goodsList.forceUpdate()
                return
            }
            this.getSearchData()
        },
        // 搜索获取数据
        getSearchData () {
            let barcode = getUrlParams().barcode
            let searchKey = getUrlParams().searchKey
            let categoryId = Number(getUrlParams().categoryId)
            let key = getUrlParams().key
            if (barcode) {
                this.barcode = barcode
                this.key = barcode
            }
            if (searchKey) {
                this.key = decodeURI(searchKey)
                this.searchKey = decodeURI(searchKey)
                this.categoryId = categoryId
            }
            if (key) {
                if (categoryId) {
                    this.key = decodeURI(key)
                    this.categoryId = categoryId
                } else {
                    this.key = decodeURI(key)
                }
            }
            let data = null
            if (this.barcode && this.key === this.barcode) { // 首页扫码跳转进来搜索所传参数
                data = {
                    currentPage: this.currentPage,
                    barcode: this.barcode,
                    orderType: this.orderType,
                    pageSize: this.pageSize
                }
            } else if (this.categoryId) {
                if (this.key === this.searchKey) { // 分类跳转进来搜索所传参数
                    data = {
                        currentPage: this.currentPage,
                        categoryId: this.categoryId,
                        orderType: this.orderType,
                        pageSize: this.pageSize
                    }
                } else { // 当前分类内搜索所传参数
                    data = {
                        currentPage: this.currentPage,
                        key: this.key,
                        categoryId: this.categoryId,
                        orderType: this.orderType,
                        pageSize: this.pageSize
                    }
                }
            } else { // 模糊搜索所传参数
                data = {
                    currentPage: this.currentPage,
                    key: this.key,
                    orderType: this.orderType,
                    pageSize: this.pageSize
                }
            }
            if (!this.key) {
                this.getSearchHistory()
                this.showSearchHistory = true
                return
            }
            this.setSearchHistory()
            this.WeChatShare()
            Axios.post('goods/goods/searchByKey.do', data).then(res => {
                if (res.respCode === 'S') {
                    if (res.data.data) {
                        let list = res.data.data
                        if (list.length === 0) {
                            this.showSearchHistory = false
                        }
                        list.forEach(item => {
                            item.minPrice = item.minPrice / 100
                            if (item.attrValues !== 'null') {
                                item.attrValues = item.attrValues.replace(/,/g,'/')
                            } else {
                                item.attrValues = ''
                            }
                        })
                        if (this.currentPage === 1) {
                            this.searchData = list
                        } else {
                            this.searchData = this.searchData.concat(list)
                        }
                        this.totalPage = res.data.totalPage

                        if (this.currentPage >= this.totalPage) {
                            this.loading = true
                            this.$refs.goodsList.forceUpdate()
                        } else {
                            this.loading = false
                        }
                    } else {
                        let list = res.data
                        if (list.length === 0) {
                            this.showSearchHistory = false
                        }
                        list.minPrice = list.minPrice / 100
                        this.searchData = []
                        this.searchData.push(list)
                    }
                } else {
                    this.barcode = ''
                    this.searchKey = ''
                    this.toast = this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt'
                    })
                    this.toast.show()
                    this.$refs.goodsList.forceUpdate()
                }
            }).catch(() => {
                this.$refs.goodsList.forceUpdate()
            })
        },
        // 直接下单
        placeOrder (index) {
            this.num = 1
            this.addCartIndex = index
            this.$refs.myPopup4.show()
        },
        // 直接购买
        toBUy () {
            let goodsSkuId = this.searchData[this.addCartIndex].goodsSkuId
            let quantity = this.num
            window.location.href = '../shopping/order.html?goodsSkuId=' + goodsSkuId + '&quantity=' + quantity
        },
        // 加入购物车减号
        reduce () {
            if (this.num > 1) {
                this.num--
            }
        },
        // 加入购物车加号
        plus () {
            if (this.num < 99)  {
                this.num++
            }
        },
        // 加入购物车按钮
        addCart () {
            Axios.post('goods/shopCar/addShopCar.do', {
                goodsSkuId: this.searchData[this.addCartIndex].goodsSkuId,
                quantity: this.num
            }).then(res => {
                if (res.respCode === 'S') {
                    const toast = this.$createToast({
                        txt: '您已提交成功<br/>请到购物车查看',
                        type: 'correct'
                    })
                    this.$refs.myPopup4.hide()
                    toast.show()
                }
            })
        },
        // 更多价格弹窗
        morePrice (e, index) {
            this.popupIndex = index
            let dom = e.currentTarget
            let bodyHeight = document.body.clientHeight
            let top = dom.previousElementSibling.getBoundingClientRect().top
            let height = dom.previousElementSibling.getBoundingClientRect().height
            let popupTop
            let size = getComputedStyle(window.document.documentElement)['font-size']
            size = Number(size.substring(0, size.length - 2))
            let popupHeight = 4.3 * size
            if ((bodyHeight - top) > (popupHeight + 10)) {
                popupTop = top + height
                this.popupTriangle = 'top'
                let left = dom.getBoundingClientRect().left - (0.05 * size) - (0.72 * size)
                this.triangleStyle = 'top: -0.33rem; left:' + left
                this.popupTop = 'top:' + popupTop
            } else {
                popupTop = top - popupHeight
                this.popupTriangle = 'bottom'
                let left = dom.getBoundingClientRect().left - (0.05 * size) - (0.72 * size)
                this.triangleStyle = 'top:' + popupHeight + ';left:' + left
                this.popupTop = 'top:' + popupTop
            }
            Axios.post('goods/goods/supermarketPriceList.do', {
                goodsSkuId: this.searchData[this.popupIndex].goodsSkuId
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.supermarketGoodsList
                    list.forEach(goods => {
                        if (goods.price == -1) {
                            goods.price = "无价格/无货"
                        } else {
                            goods.price = goods.price / 100 + "元"
                        }
                    })
                    this.marketData = list
                    dom.style.opacity = 0
                    this.showPopup = true
                }
            })
            let bodyEl = document.body
            this.scrollTop = window.scrollY
            bodyEl.style.position = 'fixed'
            bodyEl.style.top = -this.scrollTop
        },
        // 关闭更多价格弹窗
        closePopup () {
            let triangle = document.querySelectorAll('.search-goodsTriangle')
            triangle[this.popupIndex].style.opacity = 1
            let popupMarket = document.querySelector('.search-popupMarket')
            popupMarket.scrollTop = 0
            this.showPopup = false
            let bodyEl = document.body
            bodyEl.style.position = ''
            bodyEl.style.top = ''
            window.scrollTo(0, this.scrollTop)
        },
        // 保存搜索历史记录
        setSearchHistory () {
            let key = this.key
            let searchKey = getUrlParams().searchKey
            if (!key) {
                this.getSearchHistory()
                return
            }
            let barcode = this.barcode
            let data = null
            if (barcode && barcode === this.key) {
                data = {
                    searchType: 'barcode',
                    key: key
                }
            } else if (this.categoryId) {
                if (searchKey) {
                    data = {
                        searchType: 'searchKey',
                        key: key,
                        categoryId: this.categoryId
                    }
                } else {
                    data = {
                        searchType: 'category',
                        key: this.searchKey + '/' + key,
                        categoryId: this.categoryId
                    }
                }
            } else {
                data = {
                    searchType: 'key',
                    key: key
                }
            }
            let history = JSON.parse(localStorage.getItem('searchHistory'))
            let searchHistory = []
            if (!history) {
                searchHistory.push(data)
                localStorage.setItem('searchHistory', JSON.stringify(searchHistory))
            } else {
                let historyList = []
                for (let i = 0; i < history.length; i++) {
                    historyList.push(history[i].key)
                }
                if (historyList.indexOf(data.key) === -1) {
                    history.unshift(data)
                }
                this.searchHistory = history
                if (this.searchHistory.length > 10) {
                    this.searchHistory.pop()
                }
                localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
            }
        },
        // 获取搜索历史记录
        getSearchHistory () {
            let searchHistory = localStorage.getItem('searchHistory')
            if (searchHistory && searchHistory.slice(0, 1) !== '[') {
                localStorage.removeItem('searchHistory')
                return
            }
            let history = JSON.parse(searchHistory)
            if(history){
                this.searchHistory = history
            }
        },
        // 删除搜索历史记录
        delSearchHistory () {
            this.searchHistory = null
            localStorage.removeItem('searchHistory')
        },
        // 功能直达展开
        toFunction () {
            Axios.post('goods/shopCar/listAdd.do', {}).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.ShoppingCars
                    if (list.length < 100) {
                        localStorage.setItem('cartBadge', list.length)
                        this.cartBadge = list.length
                    } else {
                        localStorage.setItem('cartBadge', '99+')
                        this.cartBadge = '99+'
                    }
                    this.isFunctionMask = true
                    setTimeout(() => {
                        this.isFunction = true
                    }, 100)
                }
            })
        },
        // 功能直达关闭
        closeFunction () {
            this.isFunction = false
            setTimeout(() => {
                this.isFunctionMask = false
            }, 600)
        },
        toShare () {
            this.closeFunction()
            setTimeout(() => {
                const share = this.$refs.share
                share.show()
            }, 600)
        },
        // 跳转至自定义下单
        toCustom () {
            if (this.barcode && this.key === this.barcode) {
                window.location.href = 'custom_Order.html'
            } else {
                window.location.href = 'custom_Order.html?goodsname=' + this.key 
            }
        },
        closeShare () {
            const share = this.$refs.share
            share.hide()
        },
        // 微信JS-SDK初始化
        WeChatInit () {
            let url = location.href.split('#')[0]
            Axios.post('user/weixin/getSignature.do', {
                htmlUrl: url
            }).then(res => {
                if (res.respCode === 'S') {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: res.data.appid, // 必填，公众号的唯一标识
                        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: res.data.noncestr, // 必填，生成签名的随机串
                        signature: res.data.signature,// 必填，签名
                        jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline'] // 必填，需要使用的JS接口列表
                    })
                    
                }
            })
        },
        WeChatShare () {
            let barcode = getUrlParams().barcode
            let searchKey = getUrlParams().searchKey
            let categoryId = Number(getUrlParams().categoryId)
            let self = this
            let domain = window.location.host
            let title = null
            let param = null
            let shareUrl = null
            let htmlUrl = window.location.href
            if (JSON.stringify(getUrlParams()) !== '{}') {
                    if (/from=[^&$?]{1,}(&|$)/.test(location.search) || /isappinstalled=[^&$?]{1,}(&|$)/.test(location.search)) {
                        let newSearch = location.search.replace(/from=[^&$?]{1,}(&|$)/, '').replace(/isappinstalled=[^&$?]{1,}(&|$)/, '').replace(/&$|\?$/, '');
                        htmlUrl = location.origin + location.pathname + newSearch + location.hash
                        if (htmlUrl.indexOf('?') > -1) {
                            param = '&key='
                        } else {
                            param = '?key='
                        }
                    } else {
                        param = '&key='
                    }
            } else {
                param = '?key='
            }
            if (!barcode && !searchKey && !categoryId && this.key) {
                shareUrl = htmlUrl + param + encodeURIComponent(this.key)
                title = this.key
            } else if (categoryId && !searchKey) {
                shareUrl = htmlUrl + param + encodeURIComponent(this.key)
                title = this.key
            } else {
                shareUrl = htmlUrl
                title = '去哪买,超市比价,附近价差排行,邻居互助'
            }
            wx.ready(() => {
                wx.onMenuShareAppMessage({
                    title: title, // 分享标题
                    desc: '', // 分享描述
                    link: shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://' + domain + '/image/icon-logo.png', // 分享图标
                    trigger: (res) => {
                        
                    },
                    success: (res) => {
                        console.info('分享成功')
                        this.closeShareTips()
                    },
                    cancel: (res) => {
                        
                    },
                    fail: (res) => {
                        console.info('分享失败')
                        this.closeShareTips()
                    }
                })
                wx.onMenuShareTimeline({
                    title: title, // 分享标题
                    desc: '', // 分享描述
                    link: shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://' + domain + '/image/icon-logo.png', // 分享图标
                    success: (res) => {
                        console.info('分享成功')
                        this.closeShareTips()
                    }
                })
            })
            wx.error(function (res) {
                console.log(res.errMsg)
            })
        },
        shareTips () {
            this.closeShare()
            const shareTips = this.$refs.shareTips
            shareTips.show()
        },
        closeShareTips () {
            const shareTips = this.$refs.shareTips
            shareTips.hide()
        },
        isWeChat () {
            let ua = navigator.userAgent.toLowerCase()
            if(ua.match(/MicroMessenger/i)=="micromessenger") {
                return true
            } else {
                return false
            }
        },
        isSystem () {
            let u = navigator.userAgent
            if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
                this.isAndroid = true
                this.sendFriends = '../image/icon-sendFriendsAndroid.png'
                this.sendCircle = '../image/icon-sendCircleAndroid.png'
            } else if (u.indexOf('iPhone') > -1 ) {
                this.isAndroid = false
                this.sendFriends = '../image/icon-sendFriends.png'
                this.sendCircle = '../image/icon-sendCircle.png'
            }
        }
    }
})
